<template>
  <admin-layout>
    <div class="products-view">
      <h2 class="page-title">商品管理</h2>

      <!-- 搜索区域 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入商品名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="所属店铺">
            <el-input
              v-model="searchForm.storeName"
              placeholder="请输入店铺名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 商品列表 -->
      <el-card class="table-card" v-loading="loading">
        <el-table :data="productList" border style="width: 100%" row-key="id">
          <el-table-column label="商品图片" width="80" align="center">
            <template #default="{ row }">
              <el-image
                style="width: 50px; height: 50px"
                :src="row.image"
                :preview-src-list="[row.image]"
                fit="cover"
              >
                <template #error>
                  <div class="image-placeholder">
                    {{ row.name?.substring(0, 1) }}
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="商品名称" min-width="120" />

          <el-table-column prop="storeName" label="所属店铺" min-width="120" />

          <el-table-column prop="price" label="价格" width="100">
            <template #default="{ row }"> ¥{{ row.price }} </template>
          </el-table-column>

          <el-table-column prop="category" label="分类" width="100" />

          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.status === 'PENDING'
                    ? 'warning'
                    : row.status === 'ON_SHELF'
                    ? 'success'
                    : row.status === 'SUSPENDED'
                    ? 'danger'
                    : 'info'
                "
              >
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" min-width="160">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="220" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'PENDING'"
                size="small"
                type="success"
                @click="handleReview(row, 'approve')"
              >
                通过
              </el-button>
              <el-button
                v-if="row.status === 'PENDING'"
                size="small"
                type="danger"
                @click="handleReview(row, 'reject')"
              >
                拒绝
              </el-button>
              <el-button
                size="small"
                type="primary"
                @click="viewProductDetail(row)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="productList.length === 0 && !loading" class="empty-data">
          暂无商品数据
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="pagination.total > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            :page-size="pagination.pageSize"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>

      <!-- 审核对话框 -->
      <el-dialog
        v-model="reviewDialog.visible"
        :title="reviewDialog.title"
        width="500px"
      >
        <el-form :model="reviewForm" label-width="80px">
          <el-form-item label="审核结果">
            <el-radio-group v-model="reviewForm.status">
              <el-radio label="APPROVED">通过</el-radio>
              <el-radio label="SUSPENDED">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="审核理由"
            v-if="reviewForm.status === 'SUSPENDED'"
          >
            <el-input
              v-model="reviewForm.reason"
              type="textarea"
              rows="3"
              placeholder="请输入拒绝理由"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="reviewDialog.visible = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitReview"
              :loading="reviewDialog.loading"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 商品详情对话框 -->
      <el-dialog
        v-model="detailDialog.visible"
        title="商品详情"
        width="700px"
        class="product-detail-dialog"
      >
        <div class="product-detail" v-if="detailDialog.product">
          <div class="product-header">
            <el-image
              :src="detailDialog.product.image"
              style="width: 120px; height: 120px"
              fit="cover"
              class="product-image"
            >
              <template #error>
                <div class="image-placeholder large">
                  {{ detailDialog.product.name?.substring(0, 1) }}
                </div>
              </template>
            </el-image>
            <div class="product-title">
              <h3>{{ detailDialog.product.name }}</h3>
              <div class="product-meta">
                <el-tag
                  :type="
                    detailDialog.product.status === 'PENDING'
                      ? 'warning'
                      : detailDialog.product.status === 'ON_SHELF'
                      ? 'success'
                      : detailDialog.product.status === 'SUSPENDED'
                      ? 'danger'
                      : 'info'
                  "
                >
                  {{ getStatusLabel(detailDialog.product.status) }}
                </el-tag>
                <span class="product-price"
                  >¥{{ detailDialog.product.price }}</span
                >
              </div>
            </div>
          </div>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="所属店铺">
              {{ detailDialog.product.storeName || "未知店铺" }}
            </el-descriptions-item>
            <el-descriptions-item label="店铺ID">
              {{ detailDialog.product.storeId }}
            </el-descriptions-item>
            <el-descriptions-item label="分类">
              {{
                detailDialog.product.category ||
                `分类ID: ${detailDialog.product.categoryId || "未知"}`
              }}
            </el-descriptions-item>
            <el-descriptions-item label="库存">
              {{ detailDialog.product.stock }}
            </el-descriptions-item>
            <el-descriptions-item label="销量">
              {{ detailDialog.product.sales || 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(detailDialog.product.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDate(detailDialog.product.updateTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="商品描述" :span="2">
              {{ detailDialog.product.description || "暂无描述" }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="detail-actions">
            <el-button
              v-if="detailDialog.product.status === 'PENDING'"
              type="success"
              @click="handleReview(detailDialog.product, 'approve')"
            >
              通过审核
            </el-button>
            <el-button
              v-if="detailDialog.product.status === 'PENDING'"
              type="danger"
              @click="handleReview(detailDialog.product, 'reject')"
            >
              拒绝审核
            </el-button>
            <el-button
              v-if="detailDialog.product.status === 'ON_SHELF'"
              type="warning"
              @click="handleStatusChange(detailDialog.product, 'OFF_SHELF')"
            >
              下架商品
            </el-button>
            <el-button
              v-if="detailDialog.product.status === 'OFF_SHELF'"
              type="success"
              @click="handleStatusChange(detailDialog.product, 'ON_SHELF')"
            >
              上架商品
            </el-button>
            <el-button
              v-if="detailDialog.product.status === 'SUSPENDED'"
              type="success"
              @click="handleStatusChange(detailDialog.product, 'ON_SHELF')"
            >
              恢复商品
            </el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </admin-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as api from "@/api";
import AdminLayout from "@/components/admin/AdminLayout.vue";

// 定义商品类型
interface Product {
  id: string;
  name: string;
  storeId: string; // 店铺ID
  storeName: string; // 店铺名称
  price: number;
  image?: string;
  category?: string;
  categoryId?: string; // 分类ID
  description?: string;
  stock?: number;
  sales?: number;
  status: string;
  createTime: string;
  updateTime?: string;
}

// 商品列表
const productList = ref<Product[]>([]);

// 加载状态
const loading = ref(false);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 搜索参数
const searchForm = reactive({
  name: "",
  storeName: "",
  status: "",
});

// 状态选项
const statusOptions = [
  { value: "PENDING", label: "待审核" },
  { value: "ON_SHELF", label: "已上架" },
  { value: "OFF_SHELF", label: "已下架" },
  { value: "SUSPENDED", label: "已禁用" },
];

// 审核对话框
const reviewDialog = reactive({
  visible: false,
  title: "商品审核",
  loading: false,
  product: null as Product | null,
});

// 审核表单
const reviewForm = reactive<any>({
  id: "",
  status: "APPROVED",
  reason: "",
});

// 详情对话框
const detailDialog = reactive({
  visible: false,
  product: null as Product | null,
});

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name || undefined,
      storeName: searchForm.storeName || undefined,
      status: searchForm.status || undefined,
    };

    console.log("正在请求商品数据，参数:", params);
    const res = await api.getProducts(params);
    console.log("getProducts API响应:", res);

    const data = res.data?.data || res.data;
    console.log("解析后的数据:", data);

    if (data) {
      // 使用API文档中定义的分页格式
      // 确保将API返回的数据正确映射到我们的Product接口
      productList.value = (data.content || []).map((item) => ({
        ...item,
        // 确保店铺名称字段正确映射
        storeName: item.storeName || "未知店铺",
        // 其他字段映射
        createTime: item.createdAt || item.createTime,
      }));
      pagination.total = data.totalElements || 0;
      console.log("成功获取商品数据:", productList.value);
    } else {
      console.warn("API返回数据为空或格式不正确");
      productList.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败，请检查网络连接或API状态");
    productList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchProducts();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  pagination.currentPage = 1;
  fetchProducts();
};

// 处理页面变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchProducts();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchProducts();
};

// 获取状态标签
const getStatusLabel = (status: string): string => {
  const statusMap: Record<string, string> = {
    PENDING: "待审核",
    ON_SHELF: "已上架",
    OFF_SHELF: "已下架",
    SUSPENDED: "已禁用",
  };
  return statusMap[status] || status;
};

// 处理审核
const handleReview = async (product: Product, status: string) => {
  reviewDialog.product = product;
  reviewDialog.visible = true;
  reviewForm.id = product.id;
  // 转换状态值为API文档中定义的值
  reviewForm.status = status === "approve" ? "APPROVED" : "SUSPENDED";
  reviewForm.reason = ""; // 确保reason始终有值
};

// 提交审核
const submitReview = async () => {
  if (!reviewForm.id) return;

  reviewDialog.loading = true;
  try {
    console.log("提交商品审核，ID:", reviewForm.id, "状态:", reviewForm.status);
    // 使用API函数调用
    const response = await api.reviewProduct(
      reviewForm.id,
      reviewForm.status,
      reviewForm.status === "SUSPENDED" ? reviewForm.reason : ""
    );
    console.log("审核API响应:", response);

    // 更新本地数据
    const index = productList.value.findIndex(
      (item) => item.id === reviewForm.id
    );
    if (index !== -1) {
      // 将APPROVED映射为ON_SHELF，将SUSPENDED映射为SUSPENDED
      productList.value[index].status =
        reviewForm.status === "APPROVED" ? "ON_SHELF" : "SUSPENDED";
    }

    ElMessage.success(
      `商品${reviewForm.status === "APPROVED" ? "审核通过" : "拒绝"}成功`
    );
    reviewDialog.visible = false;

    // 刷新商品列表
    await fetchProducts();
  } catch (error) {
    console.error("审核操作失败", error);
    ElMessage.error("审核操作失败，请重试");
  } finally {
    reviewDialog.loading = false;
  }
};

// 查看商品详情
const viewProductDetail = (product: Product) => {
  detailDialog.product = product;
  detailDialog.visible = true;
};

// 格式化时间
const formatDate = (dateString: string | undefined): string => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 处理状态变更
const handleStatusChange = async (product: Product, status: string) => {
  const actionText =
    status === "ON_SHELF" ? "上架" : status === "OFF_SHELF" ? "下架" : "操作";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}商品 ${product.name} 吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    console.log(
      `执行商品${actionText}操作，ID:`,
      product.id,
      "目标状态:",
      status
    );

    // 根据API文档，使用正确的状态值
    const apiStatus = status === "ON_SHELF" ? "APPROVED" : "SUSPENDED";
    const reason = status === "SUSPENDED" ? "管理员禁用" : "";

    // 调用审核API
    const response = await api.reviewProduct(product.id, apiStatus, reason);
    console.log(`商品${actionText}API响应:`, response);

    // 更新本地数据
    product.status = status;

    // 如果是在详情对话框中操作的，更新对话框中的数据
    if (detailDialog.product && detailDialog.product.id === product.id) {
      detailDialog.product.status = status;
    }

    ElMessage.success(`${actionText}商品成功`);

    // 刷新商品列表
    await fetchProducts();
  } catch (error) {
    if (error !== "cancel") {
      console.error(`${actionText}商品失败`, error);
      ElMessage.error(`${actionText}商品失败，请重试`);
    }
  }
};

onMounted(() => {
  fetchProducts();
});
</script>

<style scoped>
.products-view {
  width: 100%;
}

.page-title {
  margin-bottom: 20px;
  color: var(--primary-dark);
  font-size: 1.5rem;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  min-height: 400px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: var(--text-secondary);
  font-size: 14px;
}

.image-placeholder {
  width: 50px;
  height: 50px;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
}

.image-placeholder.large {
  width: 120px;
  height: 120px;
  font-size: 32px;
}

.product-header {
  display: flex;
  margin-bottom: 20px;
}

.product-image {
  margin-right: 20px;
}

.product-title {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.product-title h3 {
  margin: 0 0 10px 0;
  font-size: 1.2rem;
  color: var(--text-primary);
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-price {
  font-size: 1.2rem;
  font-weight: bold;
  color: #f56c6c;
}

.product-detail-dialog .detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
